﻿using BonjourQuotation.ObjectModel.AccountData;
using BonjourQuotation.ObjectModel.LoggerData;
using BonjourQuotation.UI.Models;
using BonjourQuotation.UI.Models.AccountModel;
using BonjourQuotation.UI.Models.PartialModel;
using BonjourQuotation.UI.Models.ReportModel;
using BonjourQuotation.UI.ServiceManagers;
using iTextSharp.text;
using iTextSharp.text.pdf;
using Microsoft.Reporting.WebForms;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;


namespace BonjourQuotation.UI.Controllers
{
    public class AccountController : BaseController
    {
        AccountManager AccManager;
        BaseManager BManager;
        private readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        //
        // GET: /Report/
        [AllowAnonymous]
        public ActionResult Login()
        {
            LoginViewModel login = new LoginViewModel();
            return View(login);
        }
        [AllowAnonymous]
        public ActionResult LoginUser(LoginViewModel model, string returnUrl)
        {
            AccManager = new AccountManager();
            BManager = new BaseManager();
            LoginRequestData UserData = new LoginRequestData() { UserName = model.UserName, Password = model.Password };
            var LoginData = AccManager.Login(UserData);
            if (LoginData.IsAuth)
            {
                try
                {
                    FormsAuthentication.SetAuthCookie(UserData.UserName, false);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                LoginViewModel login = new LoginViewModel() { Message = "The user name or password provided is incorrect." };      
              //  LoginViewModel login = new LoginViewModel() { Message = LoginData.Role };
                return View("Login",login);
            }
        }
        [AllowAnonymous]
        public ActionResult Logout()
        {
            if (IsCreateSession.Any(ses => ses.Key == System.Web.HttpContext.Current.User.Identity.Name))
            {
                IsCreateSession[System.Web.HttpContext.Current.User.Identity.Name] = true;
            }
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
        [Authorize]
        [HttpGet]
        public ActionResult CreateUser()
        {
           // AccManager = new AccountManager();
            CreateUserViewModel Newuser = new CreateUserViewModel();
            Newuser.Role = InitRoles();
            this.SetPermission(Newuser, AllPermVModel);
            return View("CreateUser", Newuser);
        }
        [Authorize]
        [HttpPost]
        public ActionResult CreateUser(CreateUserViewModel model, string returnUrl)
        {
            AccManager = new AccountManager();
            CreateUserViewModel Newuser = new CreateUserViewModel();
            Newuser.Role = InitRoles();
            if (model.Password != model.RePassword)
            {
                Newuser.Message = "Passwords do not match.";
                this.SetPermission(Newuser, AllPermVModel);
                return View("CreateUser", Newuser);
            }
            CreateUserRequestData UserData = new CreateUserRequestData() { UserName = model.UserName, Password = model.Password, Role = model.SelectedRole };
            var Data = AccManager.CreateUser(UserData);
            if (Data.Error.errorCode != 0)
                Newuser.Message = Data.Error.Message;
            else
            {
                Newuser.Message = "New user sucessfully created.";
                Newuser.EmployeeID = Data.EmployeeID;
                Newuser.IsCreated = true;
            }
            this.SetPermission(Newuser, AllPermVModel);
            return View("CreateUser", Newuser);
        }
        [Authorize]
        [HttpGet]
        public ActionResult ManageUsers()
        {
            AccManager = new AccountManager();
            ManageUsersGridViewModel ManUsersVModel = new ManageUsersGridViewModel();
            this.SetPermission(ManUsersVModel, AllPermVModel);
            return View("ManageUsers", ManUsersVModel);
        }
        [Authorize]
        [HttpPost]
        public PartialViewResult LoadUsersGrid(ManageUsersGridViewModel model)
        {
            AccManager = new AccountManager();
            if (model.IsDelete)
            {
                var DeleteError = AccManager.DeleteUserByIdUsers(model.UserID);
                if (DeleteError.errorCode != 0)
                {
                    MessageBoxViewModel MessBoxforDelete = new MessageBoxViewModel()
                    {
                        Message = DeleteError.Message != null ? "Error - " + DeleteError.Message : "",
                    };
                    return PartialView("MessageBox", MessBoxforDelete);
                }
            }
            ManageUsersGridViewModel ManUsersVModel = new ManageUsersGridViewModel();
            ManUsersVModel.Rows = new List<ManageUsersGridRowViewModel>();
            var ManageUsersData = AccManager.ManageUsers();
            foreach (var user in ManageUsersData)
                ManUsersVModel.Rows.Add(new ManageUsersGridRowViewModel { Role = user.Role, UserID = user.UserID, UserName = user.UserName, EmployeeID = user.EmployeeID });
            this.SetPermission(ManUsersVModel, AllPermVModel);
            return PartialView("LoadUsersGrid", ManUsersVModel);
        }
        [Authorize]
        [HttpGet]
        public PartialViewResult LoadUserDetails(int EmployeeID)
        {
            AccManager = new AccountManager();
           
            var UserDetData = AccManager.GetUserDetails(EmployeeID);
            var UserDetViewModel = InitUserDetailsViewModel(UserDetData);
            this.SetPermission(UserDetViewModel, AllPermVModel);
            return PartialView("LoadUserDetailsGrid", UserDetViewModel);
        }
        [Authorize]
        [HttpPost]
        public PartialViewResult SaveUserDetailData(UserDetailsViewModel model)
        {
            AccManager = new AccountManager();
            var UserData = InitUserDetailsBData(model);
            var Error = AccManager.PostUserDetailsData(UserData);

            MessageBoxViewModel MessBox = new MessageBoxViewModel()
            {
                Message = Error.Message != null? "Error - "+Error.Message:"",   
            };
            return PartialView("MessageBox", MessBox);
        }
        [Authorize]
        [HttpGet]
        public ActionResult EditUser(int UserId)
        {
            AccManager = new AccountManager();
            EditUserViewModel EditUserVModel = new EditUserViewModel();
            EditUserVModel.Role = InitRoles();
            var EditUserData = AccManager.GetEditUserData(UserId);
            EditUserVModel.UserName = EditUserData.UserName;
            EditUserVModel.UserId = EditUserData.UserID;
            EditUserVModel.SelectedRole = EditUserData.SelectedRole;
            this.SetPermission(EditUserVModel, AllPermVModel);
            return View("EditUser", EditUserVModel);
        }
        [Authorize]
        [HttpPost]
        public ActionResult EditUser(EditUserViewModel model)
        {
            AccManager = new AccountManager();
            EditUserViewModel EditUserVModel = new EditUserViewModel();
            if (model.Password != model.RePassword)
            {
                EditUserVModel.Message = "Passwords do not match.";
                EditUserVModel.UserName = model.UserName;
                EditUserVModel.Role = InitRoles();
                EditUserVModel.SelectedRole = model.SelectedRole;
                this.SetPermission(EditUserVModel, AllPermVModel);
                return View("EditUser", EditUserVModel);
            }
            EditUserBData UserData = new EditUserBData { OldPassword = model.OldPassword, Password = model.Password, UserID = model.UserId, SelectedRole = model.SelectedRole, RePassword = model.RePassword, UserName = model.UserName };
            var Error = AccManager.PostEditUserData(UserData); 
            if (Error.errorCode == 0)
            {
                EditUserVModel.Message = "User data successfuly changed.";
                return RedirectToAction("ManageUsers", "Account");
            }
            else
            {
                EditUserVModel.Message = Error.Message;
                EditUserVModel.UserName = model.UserName;
                EditUserVModel.Role = InitRoles();
                EditUserVModel.SelectedRole = model.SelectedRole;
                this.SetPermission(EditUserVModel, AllPermVModel);
                return View("EditUser", EditUserVModel);
            }
           // EditUserVModel.Role = InitRoles();
            
        }
        [Authorize]
        [HttpGet]
        public PartialViewResult LoadToolTabColumnPermissions(int UserID)
        {
            AccManager = new AccountManager();
            ToolViewModel ToolVModel = new ToolViewModel();
            var ToolData = AccManager.LoadTools();
            var ProfileData = AccManager.LoadProfiles(System.Web.HttpContext.Current.User.Identity.Name);
            ToolVModel.Tool = new List<System.Web.WebPages.Html.SelectListItem>();
            ToolVModel.Profile = new List<System.Web.WebPages.Html.SelectListItem>();
            if (ToolData.Tool != null)
            {
                foreach (var tool in ToolData.Tool)
                    ToolVModel.Tool.Add(new System.Web.WebPages.Html.SelectListItem() { Text = tool.Value, Value = tool.Key.ToString() });
            }
            if (ProfileData.Profile != null)
            {
                foreach (var profile in ProfileData.Profile)
                    ToolVModel.Profile.Add(new System.Web.WebPages.Html.SelectListItem() { Text = profile.Value, Value = profile.Key.ToString() });
            }
            ToolVModel.ToolTab = new List<System.Web.WebPages.Html.SelectListItem>();
            ToolVModel.UserName = AccManager.GetUserName(UserID);
            return PartialView("ManageToolTabColumnPermissions", ToolVModel);
        }
        [Authorize]
        [HttpGet]
        public PartialViewResult LoadProfileToolTabColumnPermissions()
        {
            AccManager = new AccountManager();
            ProfileViewModel ProfileVModel = new ProfileViewModel();
            var ToolData = AccManager.LoadTools();
            var ProfileData = AccManager.LoadProfiles(System.Web.HttpContext.Current.User.Identity.Name);
            ProfileVModel.ProfileTool = new List<System.Web.WebPages.Html.SelectListItem>();
            ProfileVModel.Profile = new List<System.Web.WebPages.Html.SelectListItem>();
            if (ToolData.Tool != null)
            {
                foreach (var tool in ToolData.Tool)
                    ProfileVModel.ProfileTool.Add(new System.Web.WebPages.Html.SelectListItem() { Text = tool.Value, Value = tool.Key.ToString() });
            }
            if (ProfileData.Profile != null)
            {
                foreach (var profile in ProfileData.Profile)
                    ProfileVModel.Profile.Add(new System.Web.WebPages.Html.SelectListItem() { Text = profile.Value, Value = profile.Key.ToString() });
            }
            ProfileVModel.ProfileToolTab = new List<System.Web.WebPages.Html.SelectListItem>();
            return PartialView("ManageProfileToolTabColumnPermissions", ProfileVModel);
        }
        [Authorize]
        [HttpGet]
        public PartialViewResult LoadToolTabColumnPermissionsGrid(int UserID, int ToolTabID, int ToolID)
        {
            AccManager = new AccountManager();
            switch (ToolID)
            {
                case 1:
                    {
                        if (ToolTabID == 17)
                        {
                            var ToolTabColumnPermissionsData = AccManager.LoadToolTabColumnPermissionsCanViewCanEdit(UserID, ToolTabID);
                            ModelState.Clear();
                            return PartialView("LoadToolTabColumnPermissionsCanViewCanEditGrid", InitToolTabColumnPermissionsCanViewCanEditViewModel(ToolTabColumnPermissionsData, ToolID));
                        }
                        else
                        {
                            var ToolTabColumnPermissionsData = AccManager.LoadToolTabColumnPermissionsCanView(UserID, ToolTabID);
                            ModelState.Clear();
                            return PartialView("LoadToolTabColumnPermissionsCanViewGrid", InitToolTabColumnPermissionsCanViewViewModel(ToolTabColumnPermissionsData, ToolID));
                        }
                    }
                case 2:
                    {
                        var ToolTabColumnPermissionsData = AccManager.LoadToolTabColumnPermissionsCanViewCanEditHasFilter(UserID, ToolTabID);
                        ModelState.Clear();
                        return PartialView("LoadToolTabColumnPermissionsCanViewCanEditHasFilterGrid", InitToolTabColumnPermissionsCanViewCanEditHasFilterViewModel(ToolTabColumnPermissionsData, ToolID));
                    }
                case 3:
                    {
                        var ToolTabColumnPermissionsData = AccManager.LoadToolTabColumnPermissionsCanViewCanEdit(UserID, ToolTabID);
                        ModelState.Clear();
                        return PartialView("LoadToolTabColumnPermissionsCanViewCanEditGrid", InitToolTabColumnPermissionsCanViewCanEditViewModel(ToolTabColumnPermissionsData, ToolID));
                    }
                case 4:
                    {
                        var ToolTabColumnPermissionsData = AccManager.LoadToolTabColumnPermissionsCanView(UserID, ToolTabID);
                        ModelState.Clear();
                        return PartialView("LoadToolTabColumnPermissionsCanViewGrid", InitToolTabColumnPermissionsCanViewViewModel(ToolTabColumnPermissionsData, ToolID));
                    }
                default:
                    {
                        var ToolTabColumnPermissionsData = AccManager.LoadToolTabColumnPermissionsCanViewCanEdit(UserID, ToolTabID);
                        ModelState.Clear();
                        return PartialView("LoadToolTabColumnPermissionsCanViewCanEditGrid", InitToolTabColumnPermissionsCanViewCanEditViewModel(ToolTabColumnPermissionsData, ToolID));
                    }
            }
        }
        [Authorize]
        [HttpGet]
        public PartialViewResult LoadProfileToolTabColumnPermissionsGrid(string ProfileName, int ProfileID, int ToolTabID, int ToolID)
        {
            AccManager = new AccountManager();
            switch (ToolID)
            {
                case 1:
                    {
                        if (ToolTabID == 17)
                        {
                            var ToolTabColumnPermissionsData = AccManager.LoadProfileToolTabColumnPermissionsCanViewCanEdit(System.Web.HttpContext.Current.User.Identity.Name, ProfileName, ProfileID, ToolTabID);
                            ModelState.Clear();
                            return PartialView("LoadProfileToolTabColumnPermissionsCanViewCanEditGrid", InitToolTabColumnPermissionsCanViewCanEditViewModel(ToolTabColumnPermissionsData, ToolID));
                        }
                        else
                        {
                            var ToolTabColumnPermissionsData = AccManager.LoadProfileToolTabColumnPermissionsCanView(System.Web.HttpContext.Current.User.Identity.Name, ProfileName, ProfileID, ToolTabID);
                            ModelState.Clear();
                            return PartialView("LoadProfileToolTabColumnPermissionsCanViewGrid", InitToolTabColumnPermissionsCanViewViewModel(ToolTabColumnPermissionsData, ToolID));
                        }
                    }
                case 2:
                    {
                        var ToolTabColumnPermissionsData = AccManager.LoadProfileToolTabColumnPermissionsCanViewCanEditHasFilter(System.Web.HttpContext.Current.User.Identity.Name, ProfileName, ProfileID, ToolTabID);
                        ModelState.Clear();
                        return PartialView("LoadProfileToolTabColumnPermissionsCanViewCanEditHasFilterGrid", InitToolTabColumnPermissionsCanViewCanEditHasFilterViewModel(ToolTabColumnPermissionsData, ToolID));
                    }
                case 3:
                    {
                        var ToolTabColumnPermissionsData = AccManager.LoadProfileToolTabColumnPermissionsCanViewCanEdit(System.Web.HttpContext.Current.User.Identity.Name, ProfileName, ProfileID, ToolTabID);
                        ModelState.Clear();
                        return PartialView("LoadProfileToolTabColumnPermissionsCanViewCanEditGrid", InitToolTabColumnPermissionsCanViewCanEditViewModel(ToolTabColumnPermissionsData, ToolID));
                    }
                case 4:
                    {
                        var ToolTabColumnPermissionsData = AccManager.LoadProfileToolTabColumnPermissionsCanView(System.Web.HttpContext.Current.User.Identity.Name, ProfileName, ProfileID, ToolTabID);
                        ModelState.Clear();
                        return PartialView("LoadProfileToolTabColumnPermissionsCanViewGrid", InitToolTabColumnPermissionsCanViewViewModel(ToolTabColumnPermissionsData, ToolID));
                    }
                default:
                    {
                        var ToolTabColumnPermissionsData = AccManager.LoadProfileToolTabColumnPermissionsCanViewCanEdit(System.Web.HttpContext.Current.User.Identity.Name, ProfileName, ProfileID, ToolTabID);
                        ModelState.Clear();
                        return PartialView("LoadProfileToolTabColumnPermissionsCanViewCanEditGrid", InitToolTabColumnPermissionsCanViewCanEditViewModel(ToolTabColumnPermissionsData, ToolID));
                    }
            }
           
        }
        [Authorize]
        [HttpPost]
        public PartialViewResult SaveToolTabColumnPermisionsCanViewCanEditHasFilterData(List<ToolTabColumnPermisionsCanViewCanEditHasFilterGridRowViewModel> model)
        {
            AccManager = new AccountManager();
            var ToolTabColumn = InitToolTabColumnPermissionsCanViewCanEditHasFilterBData(model);
            var Error = AccManager.SaveToolTabColumnPermissionsCanViewCanEditHasFilter(ToolTabColumn, System.Web.HttpContext.Current.User.Identity.Name);
            MessageBoxViewModel MessBox = new MessageBoxViewModel()
            {
                Message = Error.Message != null ? "Error - " + Error.Message : "",
            };
            if (Error.Message == null)
            {
                ReloadUserPermisions(ToolTabColumn.UserID);
            }
            return PartialView("MessageBox", MessBox);
        }
        [Authorize]
        [HttpPost]
        public PartialViewResult SaveToolTabColumnPermisionsCanViewData(List<ToolTabColumnPermisionsCanViewGridRowViewModel> model)
        {
            AccManager = new AccountManager();
            var ToolTabColumn = InitToolTabColumnPermissionsCanViewBData(model);
            var Error = AccManager.SaveToolTabColumnPermissionsCanView(ToolTabColumn, System.Web.HttpContext.Current.User.Identity.Name);
            MessageBoxViewModel MessBox = new MessageBoxViewModel()
            {
                Message = Error.Message != null ? "Error - " + Error.Message : "",
            };
            if (Error.Message == null)
            {
                ReloadUserPermisions(ToolTabColumn.UserID);
            }
            return PartialView("MessageBox", MessBox);
        }
        [Authorize]
        [HttpPost]
        public PartialViewResult SaveToolTabColumnPermisionsCanViewCanEditData(List<ToolTabColumnPermisionsCanViewCanEditGridRowViewModel> model)
        {
            AccManager = new AccountManager();
            var ToolTabColumn = InitToolTabColumnPermissionsCanViewCanEditBData(model);
            var Error = AccManager.SaveToolTabColumnPermissionsCanViewCanEdit(ToolTabColumn, System.Web.HttpContext.Current.User.Identity.Name);
            MessageBoxViewModel MessBox = new MessageBoxViewModel()
            {
                Message = Error.Message != null ? "Error - " + Error.Message : "",
            };
            if (Error.Message == null)
            {
                ReloadUserPermisions(ToolTabColumn.UserID);
            }
            return PartialView("MessageBox", MessBox);
        }
        [Authorize]
        [HttpPost]
        public ActionResult SaveProfile(int ProfileID, string ProfileName)
        {
            AccManager = new AccountManager();
            var ProfileData = InitProfileBData(ProfileID, ProfileName);
            var Error = AccManager.SaveProfileData(System.Web.HttpContext.Current.User.Identity.Name, ProfileData.ProfileID, ProfileData.ProfileName);
            return Json(Error.Message);
        }
        [Authorize]
        [HttpPost]
        public PartialViewResult ApplyProfile(int UserID, int ProfileID)
        {
            AccManager = new AccountManager();
            var Error = AccManager.ApplyProfileToUser(UserID, ProfileID);
            MessageBoxViewModel MessBox = new MessageBoxViewModel()
            {
                Message = Error.Message != null ? "Error - " + Error.Message : "",
            };
            if(Error.Message == null)
            {
                ReloadUserPermisions(UserID);
            }
            return PartialView("MessageBox", MessBox);
        }
        [Authorize]
        [HttpPost]
        public ActionResult GetToolTabByToolID(int ToolID)
        {
            AccManager = new AccountManager();
            var data = AccManager.LoadToolTab(ToolID);
            List<System.Web.WebPages.Html.SelectListItem> ToolTabViewModel = new List<System.Web.WebPages.Html.SelectListItem>(); ;
            foreach (var tooltab in data.ToolTab)
            {
                ToolTabViewModel.Add(new System.Web.WebPages.Html.SelectListItem() { Text = tooltab.Value, Value = tooltab.Key.ToString() });

            }
            return Json(ToolTabViewModel);
        }
        [Authorize]
        [HttpPost]
        public ActionResult UpdateProfiles()
        {
            AccManager = new AccountManager();
            var data = AccManager.LoadProfiles(System.Web.HttpContext.Current.User.Identity.Name);
            List<System.Web.WebPages.Html.SelectListItem> ProfileViewModel = new List<System.Web.WebPages.Html.SelectListItem>(); ;
            foreach (var prof in data.Profile)
            {
                ProfileViewModel.Add(new System.Web.WebPages.Html.SelectListItem() { Text = prof.Value, Value = prof.Key.ToString() });

            }
            return Json(ProfileViewModel);
        }
        [Authorize]
        [HttpPost]
        public ActionResult GetStateByCountryID(int CountryID)
        {
            AccManager = new AccountManager();
            var data = AccManager.LoadState();
            List<System.Web.WebPages.Html.SelectListItem> StateViewModel = new List<System.Web.WebPages.Html.SelectListItem>(); ;
            foreach (var state in data)
            {
                StateViewModel.Add(new System.Web.WebPages.Html.SelectListItem() { Text = state.Value, Value = state.Key });

            }
            return Json(StateViewModel);
        }
        [Authorize]
        [HttpPost]
        public ActionResult GetCityByCountryID(int CountryID, string StateID)
        {
            AccManager = new AccountManager();
            var data = AccManager.LoadCity(CountryID, StateID);
            List<System.Web.WebPages.Html.SelectListItem> CityViewModel = new List<System.Web.WebPages.Html.SelectListItem>(); ;
            foreach (var city in data)
            {
                CityViewModel.Add(new System.Web.WebPages.Html.SelectListItem() { Text = city.Value, Value = city.Key.ToString() });

            }
            return Json(CityViewModel);
        }
        private List<System.Web.WebPages.Html.SelectListItem> InitRoles()
        {
            List<System.Web.WebPages.Html.SelectListItem> Roles = new List<System.Web.WebPages.Html.SelectListItem>();
            Roles.Add(new System.Web.WebPages.Html.SelectListItem() { Value = "admin", Text = "admin" });
            Roles.Add(new System.Web.WebPages.Html.SelectListItem() { Value = "sales", Text = "sales" });
            Roles.Add(new System.Web.WebPages.Html.SelectListItem() { Value = "accountant", Text = "accountant" });
            Roles.Add(new System.Web.WebPages.Html.SelectListItem() { Value = "operation", Text = "operation" });
            return Roles;
        }
        #region PrivateMethods
        private ToolTabColumnPermisionsCanViewCanEditHasFilterGridViewModel InitToolTabColumnPermissionsCanViewCanEditHasFilterViewModel(ToolTabColumnPermisionsCanViewCanEditHasFilterGridBData Data, int ToolID)
        {
            ToolTabColumnPermisionsCanViewCanEditHasFilterGridViewModel SetVModel = new ToolTabColumnPermisionsCanViewCanEditHasFilterGridViewModel();
            SetVModel.Rows = new List<ToolTabColumnPermisionsCanViewCanEditHasFilterGridRowViewModel>();
            SetVModel.UserID = Data.UserID;
            SetVModel.ToolTabFixedColumnCountID = Data.ToolTabFixedColumnCountID;
            SetVModel.ToolTabID = Data.ToolTabID;
            SetVModel.FixedColumnCount = Data.FixedColumnCount != null ? Convert.ToInt32(Data.FixedColumnCount) : 0;
            SetVModel.ToolID = ToolID;
            foreach (var per in Data.Rows)
            {
                SetVModel.Rows.Add(new ToolTabColumnPermisionsCanViewCanEditHasFilterGridRowViewModel
                {
                    CanEdit = per.CanEdit != null ? Convert.ToBoolean(per.CanEdit) : false,
                    CanView = per.CanView != null ? Convert.ToBoolean(per.CanView) : false,
                    HasFilter = per.HasFilter != null ? Convert.ToBoolean(per.HasFilter) : false,
                    SelectedToolTabColumnID = per.SelectedToolTabColumn,
                    LineNo = per.LineNo != null ? Convert.ToInt32(per.LineNo) : 0,
                });
            }
            SetVModel.ToolTabColumnName = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var colname in Data.ToolTabColumnName)
                SetVModel.ToolTabColumnName.Add(new System.Web.WebPages.Html.SelectListItem() { Text = colname.Value, Value = colname.Key.ToString() });
            return SetVModel;
        }
        private ToolTabColumnPermisionsCanViewGridViewModel InitToolTabColumnPermissionsCanViewViewModel(ToolTabColumnPermisionsCanViewGridBData Data, int ToolID)
        {
            ToolTabColumnPermisionsCanViewGridViewModel SetVModel = new ToolTabColumnPermisionsCanViewGridViewModel();
            SetVModel.Rows = new List<ToolTabColumnPermisionsCanViewGridRowViewModel>();
            SetVModel.UserID = Data.UserID;
            SetVModel.ToolTabID = Data.ToolTabID;
            SetVModel.ToolID = ToolID;
            foreach (var per in Data.Rows)
            {
                SetVModel.Rows.Add(new ToolTabColumnPermisionsCanViewGridRowViewModel
                {
                    CanView = per.CanView != null ? Convert.ToBoolean(per.CanView) : false,
                    SelectedToolTabColumnID = per.SelectedToolTabColumn,
                    SelectedToolTabColumnName = per.SelectedToolTabColumnName,
                });
            }
            return SetVModel;
        }
        private ToolTabColumnPermisionsCanViewCanEditGridViewModel InitToolTabColumnPermissionsCanViewCanEditViewModel(ToolTabColumnPermisionsCanViewCanEditGridBData Data, int ToolID)
        {
            ToolTabColumnPermisionsCanViewCanEditGridViewModel SetVModel = new ToolTabColumnPermisionsCanViewCanEditGridViewModel();
            SetVModel.Rows = new List<ToolTabColumnPermisionsCanViewCanEditGridRowViewModel>();
            SetVModel.UserID = Data.UserID;
            SetVModel.ToolTabID = Data.ToolTabID;
            SetVModel.ToolID = ToolID;
            foreach (var per in Data.Rows)
            {
                SetVModel.Rows.Add(new ToolTabColumnPermisionsCanViewCanEditGridRowViewModel
                {
                    CanView = per.CanView != null ? Convert.ToBoolean(per.CanView) : false,
                    CanEdit = per.CanEdit != null ? Convert.ToBoolean(per.CanEdit) : false,
                    SelectedToolTabColumnID = per.SelectedToolTabColumn,
                    SelectedToolTabColumnName = per.SelectedToolTabColumnName,
                });
            }
            return SetVModel;
        }
        private ToolTabColumnPermisionsCanViewCanEditHasFilterGridBData InitToolTabColumnPermissionsCanViewCanEditHasFilterBData(List<ToolTabColumnPermisionsCanViewCanEditHasFilterGridRowViewModel> model)
        {
            ToolTabColumnPermisionsCanViewCanEditHasFilterGridBData SetDB = new ToolTabColumnPermisionsCanViewCanEditHasFilterGridBData();
            SetDB.Rows = new List<ToolTabColumnPermisionsCanViewCanEditHasFilterGridRowBData>();
            SetDB.UserID = model[0].UserID;
            SetDB.ToolTabFixedColumnCountID = model[0].ToolTabFixedColumnCountID;
            SetDB.ToolTabID = model[0].ToolTabID;
            SetDB.FixedColumnCount = model[0].FixedColumnCount;
            SetDB.ProfileID = model[0].ProfileID;
            SetDB.ProfileName = model[0].ProfileName;
            foreach (var per in model)
            {
                SetDB.Rows.Add(new ToolTabColumnPermisionsCanViewCanEditHasFilterGridRowBData
                {
                    CanEdit = per.CanEdit,
                    CanView = per.CanView,
                    HasFilter = per.HasFilter,
                    SelectedToolTabColumn = per.SelectedToolTabColumnID,
                    LineNo = per.LineNo,
                });
            }
            return SetDB;
        }
        private ToolTabColumnPermisionsCanViewGridBData InitToolTabColumnPermissionsCanViewBData(List<ToolTabColumnPermisionsCanViewGridRowViewModel> model)
        {
            ToolTabColumnPermisionsCanViewGridBData SetDB = new ToolTabColumnPermisionsCanViewGridBData();
            SetDB.Rows = new List<ToolTabColumnPermisionsCanViewGridRowBData>();
            SetDB.UserID = model[0].UserID;
            SetDB.ToolTabID = model[0].ToolTabID;
            SetDB.ProfileID = model[0].ProfileID;
            SetDB.ProfileName = model[0].ProfileName;
            foreach (var per in model)
            {
                SetDB.Rows.Add(new ToolTabColumnPermisionsCanViewGridRowBData
                {
                    CanView = per.CanView,
                    SelectedToolTabColumn = per.SelectedToolTabColumnID,
                });
            }
            return SetDB;
        }
        private ToolTabColumnPermisionsCanViewCanEditGridBData InitToolTabColumnPermissionsCanViewCanEditBData(List<ToolTabColumnPermisionsCanViewCanEditGridRowViewModel> model)
        {
            ToolTabColumnPermisionsCanViewCanEditGridBData SetDB = new ToolTabColumnPermisionsCanViewCanEditGridBData();
            SetDB.Rows = new List<ToolTabColumnPermisionsCanViewCanEditGridRowBData>();
            SetDB.UserID = model[0].UserID;
            SetDB.ToolTabID = model[0].ToolTabID;
            SetDB.ProfileID = model[0].ProfileID;
            SetDB.ProfileName = model[0].ProfileName;
            foreach (var per in model)
            {
                SetDB.Rows.Add(new ToolTabColumnPermisionsCanViewCanEditGridRowBData
                {
                    CanEdit = per.CanEdit,
                    CanView = per.CanView,
                    SelectedToolTabColumn = per.SelectedToolTabColumnID,
                });
            }
            return SetDB;
        }
        private UserDetailsViewModel InitUserDetailsViewModel(UserDetailsBData data)
        {
            UserDetailsViewModel UserDetVModel = new UserDetailsViewModel
            {
                EmployeeID=data.EmployeeID,
                FirstName=data.FirstName,
                LastName=data.LastName,
                MiddleName=data.MiddleName,
                Title=data.Title,
                SelectedDepartmentName=data.SelectedDepartmentName,
                DateHired = data.DateHired != null ? Convert.ToDateTime(data.DateHired).ToString("dd/MMM/yy") : "",
                SelectedSupervisorID=data.SelectedSupervisorID.ToString(),
                Extension=data.Extension,
                Active = data.Active == null ? false : Convert.ToBoolean(data.Active),
                Note=data.Note,
                SocialSecurityNumber=data.SocialSecurityNumber,
                SelectedSex = data.SelectedSex != null ? Convert.ToByte(data.SelectedSex).ToString():null,
                Address=data.Address,
                SelectedCity = data.SelectedCity,
                CityID = data.CityID.ToString(),
                SelectedStateID = data.SelectedStateID,
                PostalCode = data.PostalCode,
                HomePhone = data.HomePhone,
                BirthDate = data.BirthDate != null ? Convert.ToDateTime(data.BirthDate).ToString("dd/MMM/yy") : "",
                SelectedCountry = data.SelectedCountry.ToString(),
                SelectedLCountryID = data.SelectedLCountryID.ToString(),
                EmailName=data.EmailName,
                EmrgcyContactName=data.EmrgcyContactName,
                EmrgcyContactPhone = data.EmrgcyContactPhone,
                Web=data.Web
            };
            UserDetVModel.City = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var city in data.City)
                UserDetVModel.City.Add(new System.Web.WebPages.Html.SelectListItem() { Text = city.Value, Value = city.Key.ToString() });

            UserDetVModel.DepartmentName = new List<System.Web.WebPages.Html.SelectListItem>(); 
            foreach (var dep in data.DepartmentName)
                UserDetVModel.DepartmentName.Add(new System.Web.WebPages.Html.SelectListItem() { Text = dep.Value, Value = dep.Value });

            UserDetVModel.Sex = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var sex in data.Sex)
                UserDetVModel.Sex.Add(new System.Web.WebPages.Html.SelectListItem() { Text = sex.Value, Value = sex.Key.ToString()});

            UserDetVModel.StateID = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var stID in data.StateID)
                UserDetVModel.StateID.Add(new System.Web.WebPages.Html.SelectListItem() { Text = stID.Key , Value = stID.Key });

            UserDetVModel.Country = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var cnt in data.Country)
                UserDetVModel.Country.Add(new System.Web.WebPages.Html.SelectListItem() { Text = cnt.Value, Value = cnt.Key.ToString() });
            UserDetVModel.LCountry = new List<System.Web.WebPages.Html.SelectListItem>();
            foreach (var cnt in data.LCountry)
                UserDetVModel.LCountry.Add(new System.Web.WebPages.Html.SelectListItem() { Text = cnt.Value, Value = cnt.Key.ToString() });

            UserDetVModel.QuotaRegion = new List<CheckBoxControlViewModel>();
            foreach (var QRegion in data.QuotaRegion)
                UserDetVModel.QuotaRegion.Add(new CheckBoxControlViewModel() { Id = QRegion.Key.ToString(), Name = QRegion.Value });
            UserDetVModel.QuotaSelRegions = new List<CheckBoxControlViewModel>();
            if (data.SelectedQuotaRegions != null)
                foreach (var QuotaRegion in data.SelectedQuotaRegions)
                {
                    UserDetVModel.QuotaSelRegions.Add(new CheckBoxControlViewModel { Id = QuotaRegion.ToString(), Name = QuotaRegion.ToString() });
                }
            UserDetVModel.Supervisors = new List<CheckBoxControlViewModel>();
            foreach (var Sup in data.SupervisorID)
                UserDetVModel.Supervisors.Add(new CheckBoxControlViewModel() { Id = Sup.Key.ToString(), Name = Sup.Value == null ? "Me" : Sup.Value });
            UserDetVModel.SelSupervisors = new List<CheckBoxControlViewModel>();
            if (data.SelectedSupervisorID != null)
                foreach (var SupID in data.SelectedSupervisorID)
                {
                    UserDetVModel.SelSupervisors.Add(new CheckBoxControlViewModel { Id = SupID.ToString(), Name = SupID.ToString() });
                }

            return UserDetVModel;
        }
        private UserDetailsBData InitUserDetailsBData(UserDetailsViewModel data)
        {
            UserDetailsBData UserBData = new UserDetailsBData
            {
                EmployeeID = data.EmployeeID,
                FirstName=data.FirstName,
                LastName=data.LastName,
                MiddleName=data.MiddleName,
                Title=data.Title,
                SelectedDepartmentName=data.SelectedDepartmentName,
                DateHired = data.DateHired != null ? Convert.ToDateTime(data.DateHired):(DateTime?)null,
                Extension=data.Extension,
                SocialSecurityNumber=data.SocialSecurityNumber,
                SelectedSex = data.SelectedSex != null ? Convert.ToByte(data.SelectedSex): (byte?)null,
                Address=data.Address,
                HomePhone=data.HomePhone,
                SelectedCity = data.SelectedCity,
                CityID = (data.CityID != null && data.CityID != "0") ? Convert.ToInt32(data.CityID) : (int?)null,
                SelectedStateID = data.SelectedLCountryID == "1" ? (data.SelectedStateID == "0" ? null : data.SelectedStateID) : null,
                PostalCode=data.PostalCode,
                BirthDate = data.BirthDate != null ? Convert.ToDateTime(data.BirthDate) : (DateTime?)null,
                SelectedCountry = data.SelectedCountry != null ? Convert.ToInt32(data.SelectedCountry) : (int?)null,
                SelectedLCountryID = data.SelectedLCountryID != null ? Convert.ToInt32(data.SelectedLCountryID) : (int?)null, 
                EmailName=data.EmailName,
                EmrgcyContactName=data.EmrgcyContactName,
                EmrgcyContactPhone=data.EmrgcyContactPhone,
                Active=data.Active,
                Note=data.Note

            };
            UserBData.SelectedQuotaRegions = new List<int>();
            if (data.SelectedQuotaRegions != null)
            {
                foreach (var selQuotaReg in data.SelectedQuotaRegions)
                {
                    UserBData.SelectedQuotaRegions.Add(Convert.ToInt32(selQuotaReg));
                }
            }
            UserBData.SelectedSupervisorID = new List<int>();
            if (data.SelectedSupervisors != null)
            {
                foreach (var selSupID in data.SelectedSupervisors)
                {
                    UserBData.SelectedSupervisorID.Add(Convert.ToInt32(selSupID));
                }
            }
            return UserBData;
        }
        private ProfileBData InitProfileBData(int ProfileID, string ProfileName)
        {
            ProfileBData ProfileBData = new ProfileBData
            {
                ProfileID = ProfileID,
                ProfileName = ProfileName,
            };
            return ProfileBData;
        }
        private void ReloadUserPermisions(int UserID)
        {
            var UserName = AccManager.GetUserName(UserID);
            if (IsCreateSession.Any(ses => ses.Key == UserName))
            {
                IsCreateSession[UserName] = true;
            }
        }
        #endregion
    }
}